// pages/user/user.js
//index.js
//获取应用实例
const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    hasUserInfo: false,
    canIUseGetUserProfile: true,
    isDisabled: true,
    /*booleana类不用加双引号*/
    username: '点击登录',
    defaultUrl: '/images/yuyin5.png',
    userInfo: {},
    province: '',
    store:[{name: '微信用户', phone:'',}],
    code: ''
  },
  onShow:function(){

  },
  onLoad: function () {
    wx.showShareMenu({
      // 要求小程序返回分享目标信息
      withShareTicket: true
    });
       let name = wx.getStorageSync('name');  /*当用户有更新时下面的情形发生*/
       let phone = wx.getStorageSync('phone');
        let store = this.data.store;
        store[0].name = name;
        store[0].phone = phone;
      let  openId = wx.getStorageSync('openId');
    if (name&&openId) {
      this.setData({
        hasUserInfo:true,
        store:store
      })
    }
  },
    toHide:function (all) {
   
    let mphone = all.substring(0, 3) + '****' + all.substring(7);
    return mphone;
},
  getUser(e) {
  
       
        var that = this;
        let name = '微信用户';
        //下面是通过云函数userid得到用户的openid
        let p1 = new Promise((resolve, reject) => {
          wx.cloud.callFunction({
            name: 'userid',
            complete: res => {
              var value = res.result.event.userInfo.openId;
              resolve(value)
            }
          })
        })
        Promise.all([p1]).then((result) => {
          var v = result[0];
          wx.cloud.callFunction({
              name: "getuser",
              data: {
                value:v /*用得到的值赋给云函数的value*/
              },
              complete: res => {
                var record = res.result.data;
                /*如果查询到数据,将数据记录，否则去数据库注册,改了一下，下面删除了record&&*/
                if (record.length > 0) {
                  wx.setStorageSync('openId', record[0]._openid);
                  wx.setStorageSync('name', record[0].name);
                  wx.setStorageSync('phone', record[0].baovoice);
                  var store = that.data.store;
                   store[0].name = record[0].name;
                   store[0].phone = record[0].baovoice;
                  that.setData({
                    store:store,
                    hasUserInfo:true
                  });
                } else {
                  var jointime = new Date(Date.parse(new Date()) + 60 * 60 * 1000 * 8).toISOString().substring(0, 10)
                  const _ = db.command
                  var userId = that.getUserId();
                  //定时器
                  setTimeout(() => {
                    //写入数据库
                    db.collection('users').add({
                      data: {
                        userId: userId,
                        userSweet: 10,
                        baovoice: 0,
                        name: name,
                        jointime:jointime
                        /*加的对应的上面的行*/
                      },
                      success: function () {
                        console.log('用户id新增成功')
                        db.collection('users').where({
                          userId: userId
                        }).get({
                          success: res => {
                            wx.setStorageSync('openId', res.data[0]._openid)
                          },
                          fail: err => {
                            console.log('用户_openId设置失败')
                          }
                        })
                      },
                      fail: function (e) {
                        console.log('用户id新增失败')
                      }
                    })
                  }, 200) /*这里是等上面的返回判断的时间*/
                }
              } 
        })
    })

},

getUserId: function () {
    //生产唯一id，采用一个字母或数字+1970年到现在的毫秒数+10w的一个随机数组成
    var w = "abcdefghijklmnopqrstuvwxyz0123456789",
      firstW = w[parseInt(Math.random() * (w.length))];
    var userId = firstW + (Date.now()) + (Math.random() * 100000).toFixed(0)
    wx.setStorageSync('userId', userId)
    return userId;
  },
  onShareAppMessage: function (ops) {
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      /*console.log(ops.target)*/
    }
    return {
      title: '全食烫菜',
      path: `pages/my/my`,
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
        var shareTickets = res.shareTickets;
        // if (shareTickets.length == 0) {
        //   return false;
        // }
        // //可以获取群组信息
        // wx.getShareInfo({
        //   shareTicket: shareTickets[0],
        //   success: function (res) {
        //     console.log(res)
        //   }
        // })
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  },
 goSet: function (e) {
  wx.navigateTo({
    url: '../seted/seted',
  })
  },
  gocar: function () {
    wx.navigateTo({
      url: '../buyed/buyed',
    })
  },
  goSkm: function () {
    wx.navigateTo({
      url: '../skm/skm',
    })
  },
  goadvice:function(){
    var openId = wx.getStorageSync('openId');
    if (!openId){
      wx.showToast({
        title: '请先登录！',
      })
    }else{
    wx.navigateTo({
      url: '../advice/advice',
    })
  }
  },
  goadr: function () {
    wx.navigateTo({
      url: '../address_list/address_list',
    })
  }
})